package mrms.api.web.authentication;

import org.apache.commons.io.IOUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author lenchu
 * @date 2019/02/02
 */
@WebFilter(urlPatterns = "/login", filterName = "LoginFilter")
public class AuthenticationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new MyHttpServletRequest((HttpServletRequest) request), response);
    }

    @Override
    public void destroy() {
    }
}

class MyHttpServletRequest extends HttpServletRequestWrapper {
    private final byte[] body;

    public MyHttpServletRequest(HttpServletRequest request) throws IOException {
        super(request);
        int size = request.getContentLength();
        if (size >= 0) {
            body = new byte[size];
            ServletInputStream inputStream = request.getInputStream();
            IOUtils.readFully(inputStream, body);
        } else {
            body = new byte[0];
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return bais.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
}
